import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { RouterService } from '@kylin/router';
import { HttpService } from '@kylin/http';
import { CustomValidators } from '@kylin/validators';
import { NzMessageService } from 'ng-zorro-antd';

import * as _ from 'lodash';
import { debug } from 'util';

@Component({
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less']
})
export class RegisterComponent implements OnInit {

  validateForm: FormGroup;
  loading = false;
  state = true;

  constructor(
    private routerService: RouterService,
    private fb: FormBuilder,
    private http: HttpService,
    private nzMessageService: NzMessageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      rePassword: [null, [Validators.required, this.confirmationValidator]],
      phone: [null, [Validators.required, CustomValidators.phoneNumberValidator()]],
      agree: [true]
    });
  }

  submitForm(): void {
    if (!this.validateForm.valid) {
      return;
    }
    this.loading = true;
    this.http.post('/users-anon/register', this.validateForm.value)
      .then(res => {
        if (res.resp_code === '10000') {
          this.nzMessageService.success('注册成功!');
          setTimeout(() => {
            this.routerService.navigate('/login');
          }, 1500)
        } else {
          this.nzMessageService.error(res.resp_msg);
        }

      })
      .catch(err => {
        this.nzMessageService.error(err['error']['resp_msg'] || '注册失败');
      })
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.rePassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }
}
